﻿'----------------------------------------------
'   
'   Kernel Info:---------------------------
'   Developer:              Joshua Teeter
'   Genesis:                09-02-08
'   Last Update:            09-06-28
'   Origional Version:      0.0.0.0
'   Current Version:        0.0.0.6
'   ---------------------------------------
'   
'   
'   If you modify this code please leave your name in the modified by list seperated by a comma. 
'   Changes are to be denoted in the following manner:
'                                                       * New
'                                                       ^ Updated
'                                                       - Removed
'                                                       + Added Functionality
'                                                       ! Bug unresolved
'                                                       / Bug resolved
'                                                       % Modified but not changed in a noticeable way in terms of functionality
'  
'  Please use the following as a template and copy and paste as a new comment for each modification.
'   
'   Modification Info:---------------------
'   Class Name:             ATEAList.vb
'   Modified by:            NULL
'   Last Update:            NULL
'   Current Version:        #.#.#.#
'   Changes:                 NULL
'   ---------------------------------------
'   Modification Info:---------------------
'   Class Name:             ATEAList.vb
'   Modified by:            Joshua Teeter
'   Last Update:            09-04-23
'   Current Version:        0.0.0.2
'   Changes:                 *+ ShortName in ATEA class is now updated every second, so that as time passes the accurate times are displayed
'   ---------------------------------------
'   Modification Info:---------------------
'   Class Name:             ATEAList.vb
'   Modified by:            Joshua Teeter
'   Last Update:            09-04-24
'   Current Version:        0.0.0.3
'   Changes:                 - Removed Top property. There was no easy fix for its issues.
'                           / Fixed issue when two items had the same launch time causing strange organization in the list
'   ---------------------------------------
'   Modification Info:---------------------
'   Class Name:             ATEAList.vb
'   Modified by:            Joshua Teeter
'   Last Update:            09-04-29
'   Current Version:        0.0.0.4
'   Changes:                ^ Commenting will now be done in XML for this class.
'   ---------------------------------------
'   Modification Info:---------------------
'   Class Name:             ATEAList.vb
'   Modified by:            Joshua Teeter
'   Last Update:            09-06-22
'   Current Version:        0.0.0.5
'   Changes:                * You can now create a batch file for windows start-up
'                           * New subroutines: makeBatch, loadBatch for working with the batch files.
'                           % Calls to the _engine subroutine will now create a thread (this does not change the calling process).
'   ---------------------------------------
'   Modification Info:---------------------
'   Class Name:             ATEAList.vb
'   Modified by:            Joshua Teeter
'   Last Update:            09-06-28
'   Current Version:        0.0.0.6
'   Changes:                / Removed threading because of memory leak.
'   ---------------------------------------
'
'
'
' This is a simple Sorted List implementation for the ATEA class with some added value.
'

Public Class ATEAList
    Inherits List(Of ATEA)

    '''
    ''' <FunctionName>
    ''' ATEAList.Del
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This will delete a file.
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' <name>FileName</name>
    ''' <type>String</type>
    ''' <remark>The file to delete.</remark>
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''
    Private Sub Del(ByRef FileName As String)
        System.IO.File.Delete(FileName)
        System.GC.Collect()
    End Sub

    '''
    ''' <FunctionName>
    ''' ATEAList.updateArray
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This function will add values to the array.
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' <name>temp</name>
    ''' <type>ATEA</type>
    ''' <remark>Since this is the main data struct of ATEAList it makes sense to need a full value.</remark>
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''
    Public Function updateArray(ByRef temp As ATEA) As Integer
        Try


            '
            ' Counter for location in array
            '
            Dim count As Integer = 0

            '
            ' Loop through each value in the current list
            '
            For Each i As ATEA In Me

                '
                ' If the new guy is going to launch later than the old guy then insert after
                '
                If (CDate(i._time.todaysTime) < CDate(temp._time.todaysTime)) Then
                    count += 1

                    '
                    ' Otherwise if they are equal try this
                    '
                ElseIf (CDate(i._time.todaysTime) = CDate(temp._time.todaysTime)) Then

                    '
                    ' If the new guy has a longer application name
                    '
                    If i._application.ToString < temp._application.ToString Then
                        count += 1

                        '
                        ' What if they have the same application name? well...
                        '
                    ElseIf i._application.ToString = i._application.ToString Then

                        '
                        ' Try the arguements.
                        '
                        If i._arguements.ToString < temp._arguements.ToString Then
                            count += 1
                        End If

                    End If

                End If


            Next


            '
            ' Actually place the value into the array.
            '
            Me.Insert(count, temp)


        Catch

            Dim ex As New Exception("There has been an error updating the main array. Please restart.")
            Throw ex

            Return -1

        End Try
        '
        ' pick-up the trash.
        '
        System.GC.Collect()

        '
        ' Everything passed so return nothing
        '
        Return 0

    End Function

    '''
    ''' <FunctionName>
    ''' ATEAList.SaveToFile
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This will save the ATEAList class to a file database in a bsf (bar seperated file).
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' <name>dir</name>
    ''' <type>String</type>
    ''' <remark>This is used to make the directory in which to save if it is missing.</remark>
    ''' 
    ''' <name>fileName</name>
    ''' <type>String</type>
    ''' <remark>This is used for the actual save location.</remark>
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''
    Public Sub SaveToFile(ByRef dir As String, ByRef fileName As String)


        Try
            '
            ' Make the directory if the directory does not exist yet.
            '
            System.IO.Directory.CreateDirectory(dir)
        Catch
        End Try

        Try
            '
            ' Get rid of the old file
            '
            Del(fileName)

            '
            ' Open the file for writing
            '
            Dim output As System.IO.StreamWriter = System.IO.File.AppendText(fileName)

            '
            ' Output the values in the list to the file
            '
            For Each item As ATEA In Me
                If Not item._StartUp Then
                    item.updateShortName()
                    output.WriteLine(item._application & "|" & item._time.ToString & "|" & item._Enabled & "|" & item._arguements)
                End If
            Next

            output.Close() 'close the file

        Catch e1 As Exception

            MsgBox(e1.Message)

        End Try

        makeBatch()
        loadBatch()


        MemoryManagement.FlushMemory()
    End Sub


    '''
    ''' <FunctionName>
    ''' ATEAList.loadBatch
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This subroutine will load information from a batch file.
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''
    Public Sub loadBatch()

        Dim StartupFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
        Dim batchFileName As String = My.Settings.batchFileName

        If Not StartupFolder.EndsWith("\"c) Then

            StartupFolder &= "\"

        End If

        batchFileName = StartupFolder & batchFileName

        Try

        Catch ex As Exception

        End Try
        '
        ' See if the file exists 
        '
        If System.IO.File.Exists(batchFileName) Then

            If My.Computer.FileSystem.GetFileInfo(batchFileName).Length = My.Settings.batchFileSize Then


                '
                ' Initialize the counter 
                '
                Dim count As Integer = 0


                ' Set the streamreader, the line to be read, and the array of split line contents
                Dim input As System.IO.StreamReader = System.IO.File.OpenText(batchFileName)
                Dim line As String
                Dim fields() As String ' The whole line broken by split

                ' Run trough the file and dump the information into an array, 
                ' which is re sized according to what is needed.
                While input.Peek <> -1
                    ' Read an actual line
                    line = input.ReadLine()
                    If line.StartsWith("start") And _
                    Not line = "" Then
                        line = line.Substring("start """" """.Length - 1)

                        fields = line.Split("/"c)

                        If fields.Count <> 0 Then
                            Dim path As String = fields(0).Trim(""""c)
                            Try
                                Dim arg As String = fields(1).TrimStart("/"c)

                                Dim smtwtfsTEMP As New SMTWTFS()

                                Dim ateaTEMP As New ATEA(path, True, arg, smtwtfsTEMP, True)

                                updateArray(ateaTEMP)

                            Catch

                                Dim smtwtfsTEMP As New SMTWTFS()

                                Dim ateaTEMP As New ATEA(path, True, "", smtwtfsTEMP, True)

                                updateArray(ateaTEMP)

                            End Try
                        End If

                    End If



                End While


                ' Close the file (*NOTE* This is required)
                input.Close()
            End If
        End If
        MemoryManagement.FlushMemory()


    End Sub

    '''
    ''' <FunctionName>
    ''' ATEAList.makeBatch
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This subroutine will create a batch file in the startup folder.
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''

    Public Sub makeBatch()
        Dim StartupFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
        Dim batchFileName As String = My.Settings.batchFileName

        If Not StartupFolder.EndsWith("\"c) Then

            StartupFolder &= "\"

        End If

        batchFileName = StartupFolder & batchFileName

        Try
            '
            ' Make the directory if the directory does not exist yet.
            '

        Catch
        End Try

        Try
            '
            ' Get rid of the old file
            '
            Del(batchFileName)

            '
            ' Open the file for writing
            '
            Dim output As System.IO.StreamWriter = System.IO.File.AppendText(batchFileName)
            output.WriteLine("@echo off")
            output.WriteLine("echo ""Welcome to the Rocket Launcher start-up batch file!""")
            output.WriteLine("echo ""---------------------------------------------------""")
            output.WriteLine("echo """"")

            '
            ' Output the values in the list to the file
            '
            For Each item As ATEA In Me
                If item._StartUp Then
                    If item._arguements <> "" Then
                        output.WriteLine("echo ""starting " & item._shortName & """")
                        output.WriteLine("start """" """ & item._application & """ /" & item._arguements)
                        'output.WriteLine("start   """ & item._application & """   """ & item._application & """   /" & item._arguements)

                    Else
                        output.WriteLine("echo ""starting " & item._shortName & """")
                        output.WriteLine("start """" """ & item._application & """")
                        'output.WriteLine("start   """ & item._application & """   """ & item._application & """")
                    End If

                End If

            Next

            output.WriteLine("EXIT")

            output.Close() 'close the file

        Catch

        End Try

        My.Settings.batchFileSize = My.Computer.FileSystem.GetFileInfo(batchFileName).Length
        My.Settings.Save()

        System.GC.Collect()
        MemoryManagement.FlushMemory()

    End Sub



    '''
    ''' <FunctionName>
    ''' ATEAList.Open
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This will read in the database file and update the array.
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' <name>fileName</name>
    ''' <type>String</type>
    ''' <remark>This is used for the actual save location.</remark>
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''
    Public Sub Open(ByRef fileName As String)

        frmMain.Timer1.Stop()
        Try
            '
            ' See if the file exists 
            '
            If System.IO.File.Exists(fileName) Then

                '
                ' Empty this list 
                '
                Me.Clear()

                '
                ' Initialize the counter 
                '
                Dim count As Integer = 0


                ' Set the streamreader, the line to be read, and the array of split line contents
                Dim input As System.IO.StreamReader = System.IO.File.OpenText(fileName)
                Dim line As String
                Dim fields() As String ' The whole line broken by split
                Dim tempEn As Boolean
                Dim tempArg As String
                Dim kount As Integer
                Dim fail As Boolean

                ' Run trough the file and dump the information into an array, 
                ' which is re sized according to what is needed.
                While input.Peek <> -1


                    ' Read an actual line
                    line = input.ReadLine()
                    kount += 1

                    ' If the line does not contain nothing then we proceed
                    If line <> "" Then

                        fields = line.Split("|"c) 'Split the bars out of the list and place each element into an array

                        If fields.Count = 10 Then


                            '
                            ' Time first
                            '
                            Dim time As New SMTWTFS
                            Try


                                Dim sun() As String = fields(1).Split(","c)
                                Dim mon() As String = fields(2).Split(","c)
                                Dim tue() As String = fields(3).Split(","c)
                                Dim wed() As String = fields(4).Split(","c)
                                Dim thu() As String = fields(5).Split(","c)
                                Dim fri() As String = fields(6).Split(","c)
                                Dim sat() As String = fields(7).Split(","c)
                                Dim days As New List(Of String)

                                With days
                                    .Add(sun(0))
                                    .Add(mon(0))
                                    .Add(tue(0))
                                    .Add(wed(0))
                                    .Add(thu(0))
                                    .Add(fri(0))
                                    .Add(sat(0))
                                End With


                                For Each i As String In days

                                    If i.EndsWith("AM") Or i.EndsWith("PM") Then

                                        fail = True

                                    Else

                                        fail = False

                                    End If

                                Next

                                If fail = False Then
                                    time = New SMTWTFS(sun(0), mon(0), tue(0), wed(0), thu(0), fri(0), sat(0), _
                                                        sun(1), mon(1), tue(1), wed(1), thu(1), fri(1), sat(1))
                                End If



                            Catch
                                Try
                                    time = New SMTWTFS(fields(1), fields(2), fields(3), fields(4), fields(5), fields(6), fields(7), _
                                            True, True, True, True, True, True, True)
                                Catch

                                End Try


                            End Try



                            '
                            ' Enabled
                            '
                            If fields.Count = 8 Then
                                tempEn = True
                            Else
                                tempEn = fields(8)
                            End If

                            '
                            ' Arguements
                            '
                            If fields.Count < 9 Then
                                tempArg = ""
                            Else
                                tempArg = fields(9)
                            End If

                            '
                            ' Define the ATEA
                            '

                            Dim tempsta As ATEA

                            Try
                                tempsta = New ATEA(fields(0), tempEn, tempArg, time, False)
                                updateArray(tempsta)
                            Catch

                            End Try


                            count += 1



                        End If

                    Else
                        MsgBox("The record in line" & kount & "is incomplete. The values will not be added.", MsgBoxStyle.Information)
                    End If

                End While

                ' Close the file (*NOTE* This is required)
                input.Close()

            End If
        Catch
            Try
                System.IO.File.Create(fileName)
            Catch e1 As Exception
                MsgBox(e1.Message, MsgBoxStyle.Critical, "Handled file exception")
            End Try

        End Try

        loadBatch()
        makeBatch()

        frmMain.Timer1.Start()
        System.GC.Collect()
        MemoryManagement.FlushMemory()
    End Sub


    '''
    ''' <FunctionName>
    ''' engine
    ''' </FunctionName>
    ''' 
    ''' <algorithm>
    ''' This is the core of the applicaion. message will check the current list of times against the current time and then launch
    ''' the corresponding applicaion if applicable.
    ''' </algorithm>
    ''' 
    ''' <Arguements>
    ''' nothing
    ''' </Arguements>
    ''' 
    ''' <output>nothing</output>
    '''
    Protected Friend Sub _engine()

        If Not frmMain._disabled Then


            'Dim fields() As String ' The whole line broken by split
            Dim SplitT() As String

            Dim h As String = Hour(Now).ToString
            Dim m As String = Minute(Now).ToString
            Dim s As String = Second(Now).ToString

            If m < 10 Then
                m = "0" & m
            End If
            If s < 10 Then
                s = "0" & s
            End If

            '
            ' Check each value against the current time and launch them accordingly.
            '
            For Each i As ATEA In Me

                If Not i._StartUp Then

                    If i._Enabled = True Then

                        If i._time.etodaysTime = True Then

                            SplitT = i._time.todaysTime.Split(":"c)

                            If (((CInt(h) = CInt(SplitT(0).ToString)))) Then

                                If (CInt(m) = CInt(SplitT(1).ToString)) Then

                                    If (CInt(s) = CInt(SplitT(2).ToString)) Then

                                        Try
                                            '
                                            ' Start the process
                                            '

                                            System.Diagnostics.Process.Start(i._application, i._arguements)

                                        Catch
                                            MsgBox("PROCESS FAILED TO START: " & vbCrLf & i._application, MsgBoxStyle.Critical, "ERROR")
                                        End Try

                                    End If

                                End If

                            End If
                        End If
                    End If

                End If

                i.updateShortName()
            Next
        End If
        MemoryManagement.FlushMemory()
    End Sub



End Class
